import { userToken } from '@/network/api.js'

// 存储用户信息
export function setUserStorageSync(data){
	uni.setStorageSync("openid", data.openid)
	uni.setStorageSync("user_id", data.userid)
	uni.setStorageSync("user_status", data.user_data.status)
	uni.setStorageSync("user_isBlack", data.is_black)
	uni.setStorageSync("president_status",data.user_data.president_status)
	uni.setStorageSync("token",data.user_data.token)
	let phone = data.user_data.mobile
	let name = data.user_data.name
	if (phone && phone.substring(0, 2) == '86') {
		phone = phone.substring(2, 14)
	}
	if (!phone) {
		uni.removeStorageSync("user_phone")
	}
	userToken({open_id: data.openid}).then(res=>{	
		uni.setStorageSync("token",res.data.token)
	})
	uni.setStorageSync("user_phone", phone)
	uni.setStorageSync("user_name",name)
}

//  活动状态
export function activityStatus() {
	return ['', '报名中', '已截止', '已结束', '已取消']
}

//  青创私董标签class
export function presidentClass(num) {
	let className = ''
	switch (num) {
		case 5:
			className = 'role_tag_one'
			break;
		case 6:
			className = 'role_tag_two'
			break;
		case 7:
			className = 'role_tag_three'
			break;
		case 8:
			className = 'role_tag_four'
			break;
	}
	return className
}

//  距离单位换算
export function formatDistance(mile) {
	let num = Number(mile)
	if (num >= 1000) {
		const kilometer = (num / 1000).toFixed(2)
		return `${kilometer}km`
	} else {
		return `${num}m`
	}
}


//  能量值转换
export function pointTransform(num){
	let point = Number(num)
	if(point >= 10000){
		return `${Math.floor((point / 10000) * 10) / 10}w`
	}else if(point >= 1000){
		return `${Math.floor((point / 1000) * 10) / 10}k`
	}else{
		return point
	}
}

//  拨打电话
export function call(mobile) {
	const res = uni.getSystemInfo()
	if (res.platform == 'ios') {
		uni.makePhoneCall({
			phoneNumber: mobile,
			success: () => {},
			fail() {}
		})
	} else {
		uni.showActionSheet({
			itemList: [mobile, '呼叫'],
			success: (res) => {
				if (res.tapIndex == 1) {
					uni.makePhoneCall({
						phoneNumber: mobile
					})
				}
			}
		})
	}
}

//  获取用户是否开启定位
export function userSetting(){
	let locationStatus = false
	uni.getSetting({
		success: res=>{
			if(res.authSetting['scope.userLocation']){
				locationStatus = true
			}else{
				locationStatus = false
			}
		}
	})
}

//  生成唯一id
export function generateUUID(str) {
	let uuidStr = str || 'xxxxyxxxyxyxyxy'
	var timestamp = new Date().getTime();
	var uuid = uuidStr.replace(/[xy]/g, function(c) {
		const r = (timestamp + Math.random() * 16) % 16 | 0;
		timestamp = Math.floor(timestamp / 16);
		return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
	return uuid;
}

// 格式化  扫码参数
export function InitScene(options) {
	const scene = decodeURIComponent(options);
	const obj = {};
	for (var i = 0; i < scene.split('*').length; i++) {
		const arr = scene.split('*')[i].split('/');
		obj[arr[0]] = arr[1];
	}
	return obj;
}


// 小程序版本更新
export function updateVersion() {
	const updateManager = uni.getUpdateManager();
	updateManager.onCheckForUpdate(function(res) {
		if (res.hasUpdate) {
			updateManager.onUpdateReady(function(res) {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						if (res.confirm) {
							updateManager.applyUpdate();
						}
					}
				});
			});
		}
	});

	updateManager.onUpdateFailed(function(res) {
		uni.showModal({
			title: '更新提示',
			content: '新版本更新失败，请手动更新',
			showCancel: false
		})
	});
}

// 富文本内容自适应
export function formatContent(html) {
	let content_data = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	content_data = content_data.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	content_data = content_data.replace(/<br[^>]*\/>/gi, '');
	content_data = content_data.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	return content_data;
}


// 时间转型
export function formatDate(date, isDay) {
	var date = new Date(date * 1000);
	var YY = date.getFullYear() + '-';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());

	if (isDay) {
		return YY + MM + DD
	} else {
		return YY + MM + DD + " " + hh + mm
	}
}


// 时间范围
export function dateRange(date, status) {
	const currentDate = new Date()
	const futureDate = new Date()
	futureDate.setDate(futureDate.getDate() + date)
	const params = {}
	const isOne = status == 1 ? true : false
	if (isOne) {
		params.start_time =
			`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate() + date} 00:00:00`,
			params.end_time =
			`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate() + date} 23:59:59`
	} else {
		params.start_time =
			`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()} 00:00:00`,
		params.end_time =
			`${futureDate.getFullYear()}-${futureDate.getMonth() + 1}-${futureDate.getDate()} 23:59:59`
	}
	return params
}


// 返回酒局时间
export function getDayOfWeek(date) {
	const dateData = new Date(date)
	const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	const dayIndex = dateData.getDay();
	const month = (dateData.getMonth() + 1) + '月'
	const day = dateData.getDate() + '日'
	return `${month}${day}（${daysOfWeek[dayIndex]}）`;
}


//  多级对象转为一级对象
export function flattenObj(obj, result) {
	return Object.keys(obj).reduce((result, key) => {
		// 非`null`对象递归
		if (Object(obj[key]) === obj[key]) {
			return flattenObj(obj[key], result);
		}
		result[key] = obj[key];
		return result;
	}, result || {})
}


// 防抖函数
export function debounce(fn, interval) {
	var timer;
	var gapTime = interval || 1000;
	return function() {
		clearTimeout(timer);
		var context = this;
		var args = arguments;
		timer = setTimeout(function() {
			fn.call(context, args);
		}, gapTime);
	};
}


// 按钮节流
export function throttle(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 1500
	}
	let _lastTime = null
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments)
			_lastTime = _nowTime
		}
	}
}


//  酒局列表筛选
export function teaSelectList() {
	const list = [{
			title: '选择日期',
			list: [{
				label: '默认',
				value: 0,
				check: true
			}, {
				label: '未来5天',
				value: 5,
				check: false
			}, {
				label: '未来7天',
				value: 7,
				check: false
			},{
				label: '自定义时间',
				value: 8,
				check: false
			}],
			checkName: '选择日期',
			checkValue: 0
		},
		{
			title: '选择距离',
			list: [{
					label: '默认',
					value: 10000,
					check: true
				}, {
					label: '<10km',
					value: 10000,
					check: false
				},
				{
					label: '10-30km',
					value: 30000,
					check: false
				},
				{
					label: '30-100km',
					value: 100000,
					check: false
				},
				{
					label: '地区选择',
					value: 0,
					check: false
				},
			],
			checkName: '选择距离',
			checkValue: 10000
		},
		// {
		// 	title: '类型',
		// 	list: [{
		// 		label: '全部类型',
		// 		value: 0,
		// 		check: true
		// 	}],
		// 	checkName: '全部类型',
		// 	checkValue: 0
		// },
		// {
		// 	title: '青创私董等级',
		// 	list: [{
		// 		label: '所有青创私董',
		// 		value: '',
		// 		check: true
		// 	}, {
		// 		label: '一星青创私董',
		// 		value: '5',
		// 		check: false
		// 	}, {
		// 		label: '二星青创私董',
		// 		value: '6',
		// 		check: false
		// 	}, {
		// 		label: '三星青创私董',
		// 		value: '7',
		// 		check: false
		// 	}, {
		// 		label: '四星青创私董',
		// 		value: '8',
		// 		check: false
		// 	},{
		// 		label: '五星青创私董',
		// 		value: '9',
		// 		check: false
		// 	}],
		// 	checkName: '所有青创私董',
		// 	checkValue: ''
		// },
		// {
		// 	title: '类型',
		// 	list: [{
		// 		label: '全部',
		// 		value: '',
		// 		check: true
		// 	}, {
		// 		label: '免费',
		// 		value: '1',
		// 		check: false
		// 	}, {
		// 		label: '积分',
		// 		value: '3',
		// 		check: false
		// 	}, {
		// 		label: '付费',
		// 		value: '2',
		// 		check: false
		// 	}]
		// },
		// {
		// 	title: '酒局状态',
		// 	list: [{
		// 		label: '全部',
		// 		value: '',
		// 		check: true
		// 	}, {
		// 		label: '可报名',
		// 		value: '1',
		// 		check: false
		// 	}, {
		// 		label: '已截止',
		// 		value: '3',
		// 		check: false
		// 	}, {
		// 		label: '已结束',
		// 		value: '5',
		// 		check: false
		// 	}]
		// }
	]
	return list
}

//新私董\分汇等级状态 , 传入两个参数第一个参数存在使用PartnerLevel, 否则使用PresidentLevel
export function TeaStatus(status1, status2) {
	if(parseInt(status1)){
		return PartnerLevel(status1)
	}
	return PresidentLevel(status2)
}


// 青创私董等级
export function PresidentLevel(status) {
	let PresidentName = ''
	switch (parseInt(status)) {
		case 5:
			PresidentName = '一星青创私董'
			break;
		case 6:
			PresidentName = '二星青创私董'
			break;
		case 7:
			PresidentName = '三星青创私董'
			break;
		case 8:
			PresidentName = '四星青创私董'
			break;
		case 9:
		    PresidentName = '五星青创私董'
		default:
			PresidentName = ''
	}
	return PresidentName
}


// 青创分汇等级
export function PartnerLevel(status) {
	let PresidentName = ''
	switch (parseInt(status)) {
		case 5:
			PresidentName = '一星青创分汇'
			break;
		case 6:
			PresidentName = '二星青创分汇'
			break;
		case 7:
			PresidentName = '三星青创分汇'
			break;
		case 8:
			PresidentName = '四星青创分汇'
			break;
		case 9:
		    PresidentName = '五星青创分汇'
		default:
			PresidentName = ''
	}
	return PresidentName
}


//  酒局详情按钮数据
export function TeaBtnList() {
	const list = [{
			id: 0,
			name: '返回',
			click: 'onBack',
			bgColor: '#A7B0C0'
		},
		{
			id: 1,
			name: '邀请酒局',
			click: 'share',
			bgColor: '#F96257'
		},
		{
			id: 2,
			name: '签到',
			click: 'signIn',
			bgColor: '#05B2C6'
		},
		{
			id: 3,
			name: '结束酒局',
			click: 'finish',
			bgColor: '#EF1F1F'
		},
		{
			id: 4,
			name: '评价',
			click: 'assess',
			bgColor: '#2C76ED'
		},
		{
			id: 5,
			name: '立即报名',
			click: 'signUp',
			bgColor: '#EF1F1F'
		},
		/* {
			id: 6,
			name: '报名费提现',
			click: 'withdraw',
			bgColor: '#EF1F1F'
		}, */
		{
			id: 6,
			name: '已结束',
			// click: 'withdraw',
			bgColor: '#EF1F1F'
		},
		{
			id: 7,
			name: '已截止',
			click: '',
			bgColor: '#31396A'
		},
		{
			id: 8,
			name: '已失效',
			click: '',
			bgColor: '#31396A'
		},
		{
			id: 9,
			name: '审核中',
			click: '',
			bgColor: '#31396A'
		},
		{
			id: 10,
			name: '已报名',
			click: '',
			bgColor: '#31396A'
		},
		{
			id: 11,
			name: '任务',
			click: 'mission',
			bgColor: '#F96257'
		}
	]
	return list
}


//  判断对象是否有空值
export function hasEmptyValue(obj) {
	for (let key in obj) {
		if (obj[key] === null || obj[key] === undefined || obj[key] === '' || obj[key].length == 0) {
			return false;
		}
	}
	return true;
}


//  朋友圈进入访问判断
export function momentJudge() {
	if (!uni.getStorageSync("user_id")) {
		uni.showToast({
			icon: "none",
			duration: 2000,
			title: "请先点击下方'前往小程序'方可对接",
		})
		return false
	} else {
		return true
	}
}


//  人脉筛选
export function groupSelectList() {
	const list = [{
		id: 1,
		title: '青创私董',
		list: [{
			label: '只看青创私董',
			value: 1,
			check: false
		}]
	}, {
		id: 2,
		title: '老乡',
		list: [{
			label: '只看老乡',
			value: 1,
			check: false
		}]
	}, {
		id: 3,
		title: '性别',
		list: [{
				label: '全部',
				value: 0,
				check: true
			},
			{
				label: '男',
				value: 1,
				check: false
			},
			{
				label: '女',
				value: 2,
				check: false
			}
		]
	}, {
		id: 4,
		title: '好友',
		list: [{
			label: '只看好友',
			value: 1,
			check: false
		}]
	}, {
		id: 5,
		title: '来友',
		list: [{
			label: '只看来友',
			value: 1,
			check: false
		}]
	}, {
		id: 6,
		title: '行业',
		list: []
	}, ]
	return list
}


//  预览pdf
export function openDocumentPdf(val){
	wx.downloadFile({
		url: val,
		header: {
			"Content-Type": "application/pdf;charset=UTF-8"
		},
		success: function(res) {
			if (res.statusCode == 200) {
				const filePath = res.tempFilePath;
				uni.showLoading({
					title: '正在打开',
					mask: true
				})
				wx.openDocument({
					filePath: filePath,
					fileType: 'pdf',
					showMenu: true,
					success: function(res) {
						uni.hideLoading()
					},
					fail: function(err) {
						uni.hideLoading()
					}
				});
			}
		},
		fail: function(err) {
			uni.hideLoading()
		}
	});
}